package com.chenwang.measure.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.TextView;

import com.chenwang.measure.MyApp;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.ObserverOnNext;
import com.chenwang.measure.model.bean.LocationBean;
import com.chenwang.measure.ui.dialog.DeviceMoadeLoadingDialog;
import com.chenwang.measure.utils.BluetoothUtil;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyCrashHandler;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxTime;
import com.chenwang.measure.utils.RxUtils;
import com.chenwang.measure.utils.SharePreferenceUtils;


import java.io.IOException;
import java.io.OutputStream;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

//三种模式设定
public class DeviceModeActivity extends BaseActivity {


    @BindView(R.id.tv_1)
    TextView mTv1;
    @BindView(R.id.cl_1)
    ConstraintLayout mCl1;
    @BindView(R.id.tv_2)
    TextView mTv2;
    @BindView(R.id.cl_2)
    ConstraintLayout mCl2;
    @BindView(R.id.tv_3)
    TextView mTv3;
    @BindView(R.id.cl_3)
    ConstraintLayout mCl3;
    @BindView(R.id.reset)
    TextView mTvReset;
    private DeviceMoadeLoadingDialog mDialog;

    @Override
    public int setLayoutId() {
        return R.layout.activity_device_mode;
    }


    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        initMode();
    }

    //显示当前模式  1 sbas  2cors  3电台
    private void initMode() {
        switch (SharePreferenceUtils.getInt(this, "device_mode", 0)) {
            case 0:
                mCl3.setBackgroundResource(R.drawable.corners6_s1);
                mTv3.setTextColor(getResources().getColor(R.color.black_333333));
                mCl2.setBackgroundResource(R.drawable.corners6_s1);
                mTv2.setTextColor(getResources().getColor(R.color.black_333333));
                mCl1.setBackgroundResource(R.drawable.corners6_s1);
                mTv1.setTextColor(getResources().getColor(R.color.black_333333));
                break;
            case 1:
                mCl1.setBackgroundResource(R.drawable.corners6_s1_bule);
                mTv1.setTextColor(getResources().getColor(R.color.colorBlue));
                break;
            case 2:
                mCl3.setBackgroundResource(R.drawable.corners6_s1);
                mTv3.setTextColor(getResources().getColor(R.color.black_333333));
                mCl2.setBackgroundResource(R.drawable.corners6_s1_bule);
                mTv2.setTextColor(getResources().getColor(R.color.colorBlue));
                mCl1.setBackgroundResource(R.drawable.corners6_s1);
                mTv1.setTextColor(getResources().getColor(R.color.black_333333));
                break;
            case 3:
                mCl3.setBackgroundResource(R.drawable.corners6_s1_bule);
                mTv3.setTextColor(getResources().getColor(R.color.colorBlue));
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationBean.getInstance().setOkMsg(false);
    }

    @OnClick({R.id.cl_1, R.id.cl_2, R.id.cl_3,R.id.reset})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.reset:
                if (MyApp.getBluetoothSocket() !=null && LocationBean.getInstance().isState()){
                 showDialogBack();

                }else {
                    MyToast.show("设备未连接");
                }
                break;
            case R.id.cl_1://sbas
                if (MyApp.getBluetoothSocket() != null) {
                    Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                            showDialog();
                            OutputStream outStream = MyApp.getBluetoothSocket().getOutputStream();
                            LocationBean.getInstance().setOkMsg(true);
                            //关闭电台模式
                            if (SharePreferenceUtils.getInt(DeviceModeActivity.this, "device_mode", 0)==3){
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");//先将保存ok字符串设为""
                                outStream.write("set datalink radio off\r\n".getBytes());
                                FileUtils.log("关闭电台指令：" + "set datalink radio off");
                                Thread.sleep(1000);
                                //如果返回的是 OK！ 表示指令发送成功
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("关闭电台");
                                } else {
                                    //指令没有解析到OK！回令 表示发送失败 不在发送指令
                                    FileUtils.log("发送失败 关闭电台指令：" + "set datalink radio off");
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }
                                outStream.write("interfacemode com2 compass on\r\n".getBytes());
                                FileUtils.log("关闭电台指令：" + "interfacemode com2 compass on");

                            }

                            //关闭cors
                            if (SharePreferenceUtils.getInt(DeviceModeActivity.this, "device_mode", 0) == 2) {
                                LocationBean.getInstance().setOk(" ");
                                MyApp.getBluetoothSocket().getOutputStream().write("tst setcors disconnect\r\n".getBytes());
                                FileUtils.log("关闭cors指令：" + "tst setcors disconnect");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("关闭cors");

                                } else {
                                    FileUtils.log("发送失败 关闭cors指令：" + "tst setcors disconnect");
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);
                                }

                            }

                            //开始发送sbas指令
                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(1000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("sbascontrol enable msas\r\n".getBytes());
                                FileUtils.log("指令：" + "sbascontrol enable msas");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {

                                } else {
                                    FileUtils.log("发送失败指令：" + "sbascontrol enable msas");

                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }

                            }

                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("rtkobsmode 3\r\n".getBytes());
                                FileUtils.log("指令：" + "rtkobsmode 3");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {


                                } else {
                                    FileUtils.log("发送失败指令：" + "rtkobsmode 3");
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }

                            }
                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("saveconfig\r\n".getBytes());
                                FileUtils.log("指令：" + "saveconfig");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    emitter.onNext(true);

                                } else {
                                    FileUtils.log("发送失败指令：" + "saveconfig");
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }

                            }


                        }
                    }).compose(RxUtils.<Boolean>io_main())
                            .subscribe(new ObserverOnNext<Boolean>() {
                                @Override
                                public void onNext(Boolean aBoolean) {
                                    LocationBean.getInstance().setOkMsg(false);
                                    dismissDialog();
                                    if (aBoolean){
                                        MyToast.show("sbas模式启动成功");
                                        SharePreferenceUtils.putInt(DeviceModeActivity.this, "device_mode", 1);
                                        mCl1.setBackgroundResource(R.drawable.corners6_s1_bule);
                                        mTv1.setTextColor(getResources().getColor(R.color.colorBlue));
                                        mCl2.setBackgroundResource(R.drawable.corners6_s1);
                                        mTv2.setTextColor(getResources().getColor(R.color.black_333333));
                                        mCl3.setBackgroundResource(R.drawable.corners6_s1);
                                        mTv3.setTextColor(getResources().getColor(R.color.black_333333));
                                    }else {
                                        MyToast.show("sbas模式启动失败 请重试");
                                    }

                                }
                            });

                } else {
                    MyToast.show("设备未连接");
                }

                break;
            case R.id.cl_2://cors
                Intent intent = new Intent(this,CorsActivity.class);
                startActivityForResult(intent,1 );
                break;
            case R.id.cl_3://电台模式
                if (MyApp.getBluetoothSocket() != null) {
                    Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                            showDialog();
                            LocationBean.getInstance().setOkMsg(true);
                            OutputStream outStream = MyApp.getBluetoothSocket().getOutputStream();

                            //关闭sbas
                            if (SharePreferenceUtils.getInt(DeviceModeActivity.this, "device_mode", 0)==1){
                                outStream.write("sbascontrol disable msas\n".getBytes());
                                Thread.sleep(2000);
                                outStream.write("rtkobsmode 0\r\n".getBytes());
                             /*   LocationBean.getInstance().setOk(" ");
                                outStream.write("sbascontrol disable msas\n".getBytes());
                                FileUtils.log("关闭SBAS指令：" + "sbascontrol disable msas");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("关闭sbas 1ok");
                                    FileUtils.log("发送失败 关闭SBAS指令：" + "sbascontrol disable msas");

                                } else {
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);
                                }



                                if (LocationBean.getInstance().isOkMsg()) {
                                    Thread.sleep(2000);
                                    LocationBean.getInstance().setOk(" ");
                                    outStream.write("rtkobsmode 0\r\n".getBytes());
                                    FileUtils.log("关闭SBAS指令：" + "rtkobsmode 0");
                                    Thread.sleep(1000);
                                    if (LocationBean.getInstance().getOk().equals("OK!")) {
                                        MyLogger.i("关闭sbas 2ok");

                                    } else {
                                        FileUtils.log("发送失败 关闭SBAS指令：" + "rtkobsmode 0");

                                        emitter.onNext(false);
                                        emitter.onComplete();
                                        LocationBean.getInstance().setOkMsg(false);
                                    }

                                }*/
                            }

                            //关闭cors
                            if (SharePreferenceUtils.getInt(DeviceModeActivity.this, "device_mode", 0) == 2) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                MyApp.getBluetoothSocket().getOutputStream().write("tst setcors disconnect\r\n".getBytes());
                                FileUtils.log("关闭cors指令：" + "tst setcors disconnect");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("关闭cors");

                                } else {
                                    FileUtils.log("发送失败 关闭cors指令：" + "tst setcors disconnect");

                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);
                                }

                            }

                            //开始发送电台指令
                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("set datalink radio on\r\n".getBytes());
                                FileUtils.log("指令：" + "set datalink radio on");
                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("1ok");

                                } else {
                                    FileUtils.log("发送失败指令：" + "set datalink radio on");

                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }

                            }
                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("interfacemode com2 auto auto on\r\n".getBytes());
                                FileUtils.log("指令：" + "interfacemode com2 auto auto on");
                                    Thread.sleep(1000);
                                    if (LocationBean.getInstance().getOk().equals("OK!")) {
                                        MyLogger.i("2ok");
                                    } else {
                                        FileUtils.log("发送失败指令：" + "interfacemode com2 auto auto on");

                                        emitter.onNext(false);
                                        emitter.onComplete();
                                        LocationBean.getInstance().setOkMsg(false);
                                    }

                            }

                            Thread.sleep(2000);
                            LocationBean.getInstance().setOk(" ");
                            outStream.write("$$0000A4600500132*46\r\n".getBytes());
                            FileUtils.log("指令：" + "$$0000A4600500132*46");
                            Thread.sleep(1000);

                            if (LocationBean.getInstance().isOkMsg()) {
                                Thread.sleep(2000);
                                LocationBean.getInstance().setOk(" ");
                                outStream.write("saveconfig\r\n".getBytes());
                                FileUtils.log("指令：" + "saveconfig");

                                Thread.sleep(1000);
                                if (LocationBean.getInstance().getOk().equals("OK!")) {
                                    MyLogger.i("5ok");
                                    emitter.onNext(true);

                                } else {
                                    MyLogger.i("发送失败：saveconfig");
                                    emitter.onNext(false);
                                    emitter.onComplete();
                                    LocationBean.getInstance().setOkMsg(false);

                                }



                            }


                        }
                    }).compose(RxUtils.<Boolean>io_main())
                            .subscribe(new ObserverOnNext<Boolean>() {
                                @Override
                                public void onNext(Boolean aBoolean) {
                                    LocationBean.getInstance().setOkMsg(false);
                                    if (aBoolean){
                                        SharePreferenceUtils.putInt(DeviceModeActivity.this, "device_mode", 3);
                                        MyToast.show("电台模式设定成功");
                                        mCl3.setBackgroundResource(R.drawable.corners6_s1_bule);
                                        mTv3.setTextColor(getResources().getColor(R.color.colorBlue));
                                        mCl2.setBackgroundResource(R.drawable.corners6_s1);
                                        mTv2.setTextColor(getResources().getColor(R.color.black_333333));
                                        mCl1.setBackgroundResource(R.drawable.corners6_s1);
                                        mTv1.setTextColor(getResources().getColor(R.color.black_333333));
                                    }else {
                                        MyToast.show("电台模式启动失败 请重试");
                                    }
                                    dismissDialog();
                                }
                            });

                } else {
                    MyToast.show("请确保设备已连接");
                }
                break;
        }
    }



    //显示对话框
    private void showDialog() {
        mDialog = new DeviceMoadeLoadingDialog();
        mDialog.show(getSupportFragmentManager(), "");
    }

    //关闭对话框
    private void dismissDialog() {
        if (mDialog != null&& mDialog.isAdded()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    //
    private void showDialogBack(){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("复位");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("是否复位重启");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                                showLoading("正在重启 请稍后");
                                MyApp.getBluetoothSocket().getOutputStream().write("freset\r\n".getBytes());
                                Thread.sleep(60000);
                                emitter.onNext(true);
                            }
                        }).compose(RxUtils.<Boolean>io_main()).subscribe(new ObserverOnNext<Boolean>() {
                            @Override
                            public void onNext(Boolean aBoolean) {
                                SharePreferenceUtils.putInt(DeviceModeActivity.this, "device_mode", 0);
                                initMode();
                                dismissLoading();

                            }
                        });



                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }



}
